package com.zyw.srsb.bulletin.service.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyw.srsb.bulletin.dto.event.IsAuthEvent;
import com.zyw.srsb.bulletin.dto.event.LinkEvent;
import com.zyw.srsb.bulletin.dto.response.LinkResponse;
import com.zyw.srsb.bulletin.entity.SrsbBulletinBoard;
import com.zyw.srsb.bulletin.entity.SrsbBulletinLinkList;
import com.zyw.srsb.bulletin.entity.SrsbBulletinLoginRecord;
import com.zyw.srsb.bulletin.mapper.SrsbBulletinLinkListMapper;
import com.zyw.srsb.bulletin.service.SrsbBulletinBoardService;
import com.zyw.srsb.bulletin.service.SrsbBulletinLinkListService;
import com.zyw.srsb.bulletin.util.IPUtils;
import com.zyw.srsb.common.core.exception.ValidateCodeException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

/**
 * 看板外链
 *
 * @author 朱耀威
 * @date 2022-01-23 14:53:40
 */
@Service
public class SrsbBulletinLinkListServiceImpl extends ServiceImpl<SrsbBulletinLinkListMapper, SrsbBulletinLinkList> implements SrsbBulletinLinkListService {

	@Resource
	SrsbBulletinLoginRecordServiceImpl srsbBulletinLoginRecordService;

	@Resource
	SrsbBulletinBoardService srsbBulletinBoardService;

	@Value("${auth.link-key}")
	private String linkKey;
	/**
	 * 创建外链
	 *
	 * @param event
	 * @return
	 */
	@Override
	public LinkResponse createLink(LinkEvent event) {
		LinkResponse linkResponse = new LinkResponse();

		DateTime now = DateTime.now();
		// 如果结束时间为空，则设置时间为 9999/12/31 23:59:59
		if (ObjectUtil.isEmpty(event.getEndTime())){
			event.setEndTime(LocalDateTime.of(9999,12,31,23,59,59));
		}
		Map<String,Object> payload = new HashMap<String,Object>();
		// 签发时间
		payload.put(JWTPayload.ISSUED_AT, now);
		// 过期时间
		payload.put(JWTPayload.EXPIRES_AT, event.getEndTime());
		// 生效时间
		payload.put(JWTPayload.NOT_BEFORE, now);
		// 载荷
		payload.put("result",event);
		String token = JWTUtil.createToken(payload, linkKey.getBytes());

		linkResponse.setUrl(event.getEntryUrl()+"?secretKey="+token);
		linkResponse.setSecrecyKey(token);
		linkResponse.setEndTime(event.getEndTime());

		// 保存外链
		SrsbBulletinLinkList srsbBulletinLinkList = new SrsbBulletinLinkList();
		srsbBulletinLinkList.setEndTime(event.getEndTime());
		srsbBulletinLinkList.setBoardId(event.getBoardId());
		srsbBulletinLinkList.setCiphertext(token);
		srsbBulletinLinkList.setEntryUrl(linkResponse.getUrl());
		srsbBulletinLinkList.setStatus(event.getStatus());
		this.save(srsbBulletinLinkList);

		return linkResponse;
	}

	@Override
	public void isAuth(IsAuthEvent event, HttpServletRequest request) {
		String secretKey = event.getToken();
		SrsbBulletinLoginRecord srsbBulletinLoginRecord = new SrsbBulletinLoginRecord();
		srsbBulletinLoginRecord.setIp(IPUtils.getRealIP(request));
		srsbBulletinLoginRecord.setRequestText(JSONUtil.toJsonStr(request.getHttpServletMapping()));
		srsbBulletinLoginRecord.setCiphertext(secretKey);
		srsbBulletinLoginRecord.setUrl(event.getUrl());
		int flag = 0;

		try {
			// 解密yokrn
			JWT jwt = JWTUtil.parseToken(secretKey);
			jwt.setKey(linkKey.getBytes());
			if (!jwt.verify()){
				flag = 1;
			}
		}catch (Exception e){}

		// 查询外链信息
		LambdaQueryWrapper<SrsbBulletinLinkList> linkListLambdaQueryWrapper = new LambdaQueryWrapper<>();
		linkListLambdaQueryWrapper.eq(SrsbBulletinLinkList::getCiphertext,secretKey);
		// 查询外链
		SrsbBulletinLinkList srsbBulletinLinkList = this.baseMapper.selectOne(linkListLambdaQueryWrapper);

		// 如果外链为空或者状态为失效或者结束时间小于当前时间
		if (ObjectUtil.isEmpty(srsbBulletinLinkList)||srsbBulletinLinkList.getStatus().intValue()==0||srsbBulletinLinkList.getEndTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()<System.currentTimeMillis()){
			flag = 2;
		}

		// 查询看板
		if (ObjectUtil.isNotEmpty(srsbBulletinLinkList)){
			SrsbBulletinBoard srsbBulletinBoard = srsbBulletinBoardService.getBaseMapper().selectById(srsbBulletinLinkList.getBoardId());
			if (ObjectUtil.isNotEmpty(srsbBulletinBoard)){
				// 看板未发布设置值
				if ("0".equals(srsbBulletinBoard.getStatus())){
					flag = 3;
				}
				srsbBulletinLoginRecord.setName(srsbBulletinBoard.getName());
				srsbBulletinLoginRecord.setIntroduce(srsbBulletinBoard.getIntroduce());

			}
		} else {
			srsbBulletinLoginRecord.setName(event.getName());
		}
		switch (flag){
			case 1:srsbBulletinLoginRecord.setResponseText("无效的key");srsbBulletinLoginRecord.setStatus("0");srsbBulletinLoginRecordService.save(srsbBulletinLoginRecord);throw new ValidateCodeException("无效的key");
			case 2:srsbBulletinLoginRecord.setResponseText("外链已经失效");srsbBulletinLoginRecord.setStatus("0");srsbBulletinLoginRecordService.save(srsbBulletinLoginRecord);throw new ValidateCodeException("外链已经失效");
			case 3:srsbBulletinLoginRecord.setResponseText("看板已经停用");srsbBulletinLoginRecord.setStatus("0");srsbBulletinLoginRecordService.save(srsbBulletinLoginRecord);throw new ValidateCodeException("看板已经停用");
			default:srsbBulletinLoginRecord.setResponseText("成功");srsbBulletinLoginRecord.setStatus("1");srsbBulletinLoginRecordService.save(srsbBulletinLoginRecord);break;
		}
	}
}
